package com.center.growcenterserver.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/map")
public class MapController {

    @Value("${amap.api.key}")
    private String amapApiKey;

    /**
     * 根据地址搜索经纬度（地理编码）
     */
    @GetMapping("/geocode")
    public ResponseEntity<?> geocode(@RequestParam String address) {
        String url = "https://restapi.amap.com/v3/geocode/geo?address=" + address + "&key=" + amapApiKey;
        RestTemplate restTemplate = new RestTemplate();
        try {
            String response = restTemplate.getForObject(url, String.class);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage());
        }
    }

    /**
     * 根据经纬度搜索地址（逆地理编码）
     */
    @GetMapping("/reverse-geocode")
    public ResponseEntity<?> reverseGeocode(@RequestParam double longitude, @RequestParam double latitude) {
        String url = "https://restapi.amap.com/v3/geocode/regeo?location=" + longitude + "," + latitude + "&key=" + amapApiKey;
        RestTemplate restTemplate = new RestTemplate();
        try {
            String response = restTemplate.getForObject(url, String.class);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage());
        }
    }
}
